import NavBar from '@/components/menus/NavBar';
import { Editor, View } from '@tarojs/components';
import Taro, { useDidHide, useDidShow, useLoad } from '@tarojs/taro';
import { Arrow, Cross, PhotoOutlined, SmileOutlined } from '@taroify/icons';
import { useEffect, useState } from 'react';
import MyInput from '@/components/common/MyInput';
import { Button, Divider, FixedView, Image } from '@taroify/core';
import FileTools from '@/components/common/FileTools';
import { strToArray, toast } from '@/utils';
import { getUser } from '@/utils/auth';
import xingqiu from '@/assets/images/tabbar/xingqiu.png';
import topic from '@/assets/images/icon/topic.png';
import { selectSectorPage, submitPostInfoApi } from '@/api';
import { ResponseListType } from '@/types/response';
import { RenderTagList, RenderTitle } from '@/utils/render';

export default () => {
  const user = getUser();
  const [index, setIndex] = useState(0);
  const [images, setImages] = useState<string[]>([]);
  const [editorCtx, setEditorCtx] = useState<any>();
  const [title, setTitle] = useState('');
  const [bars, setBars] = useState<any>([]);
  const [parentId, setParentId] = useState<string | number>('');
  useDidShow(() => Taro.hideTabBar());
  useLoad(() => {
    selectSectorPage({ checkFlag: '1', pageNum: 1, pageSize: 1000 }).then(
      (res: ResponseListType) => {
        setBars(res.records);
      },
    );
  });
  const handleImage = res => {
    strToArray(res).forEach(item => {
      if (editorCtx) {
        editorCtx.insertImage({
          src: item,
          success: () => setImages([...images, item]),
        });
      }
    });
  };

  useEffect(() => {
    Taro.createSelectorQuery()
      .select('#editor')
      .context(res => {
        setEditorCtx(res.context);
      })
      .exec();
  }, []);

  function back() {
    setTimeout(() => {
      Taro.showTabBar();
      Taro.switchTab({ url: '/pages/index/index' });
    }, 1000);
  }
  function publicArticle() {
    editorCtx.getContents().then(content => {
      if (title.trim() == '') return toast('请输入标题');
      if (content.text.trim() == '') return toast('请输入正文内容');
      if (parentId == '') return toast('请选择板块');
      const params = {
        typeFlag: index,
        tagName: '测试',
        sectorFlag: 3,
        parentId,
        contextUrl: images.join(','),
        context: content.html,
        userId: user.kid,
        title,
      };
      submitPostInfoApi(params).then(() => back());
    });
  }
  return (
    <NavBar
      left={<Cross size={22} onClick={back} />}
      title={RenderTitle({ handle: setIndex })}
    >
      <View>
        <MyInput
          placeholderStyle="text-lg"
          className="mt-2 "
          placeholder="请输入完整帖子标题（5-24个字）"
          change={setTitle}
          textSize={22}
          maxLength={24}
        />
        <Divider />
        <Editor
          id="editor"
          className="p-3 h-72"
          placeholder="请输入正文(支持图片和文字混排，最多添加6张图片)"
        />
        <View className="px-4 py-2 flex flex-col gap-2 text-sm">
          <View className="flex justify-between items-center">
            <View className="flex gap-2 items-center">
              <Image src={xingqiu} width={40} height={40} />
              <View
                style={{
                  color: parentId ? '#7C94DD' : '#000',
                }}
              >
                选择的板块
              </View>
            </View>
            <View className="flex items-center text-xs text-gray-400">
              <View>选择合适的把会有更多点赞哦</View>
              <Arrow />
            </View>
          </View>
          <RenderTagList
            onClick={id => setParentId(id)}
            tags={bars.map(el => ({
              id: el.kid,
              image: el.sectorUrl,
              label: el.sectorName,
            }))}
          />
          <View className="flex justify-between items-center">
            <View className="flex gap-2 items-center">
              <Image src={topic} width={30} height={30} />
              添加话题
            </View>
            <View className="flex items-center text-xs text-gray-400">
              <View>添加话题会让内容更多的曝光</View>
              <Arrow />
            </View>
          </View>
        </View>

        <FixedView position="bottom" className="bg-white">
          <Button color="primary" className="w-full" onClick={publicArticle}>
            发布
          </Button>
          <View className="pb-3">
            <FileTools
              handleBack={() => editorCtx.undo()}
              changeImage={handleImage}
              changeEmoji={handleImage}
            />
          </View>
        </FixedView>
      </View>
    </NavBar>
  );
};
